"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 功能
Case Name   : 降备过程中，网络故障
Create At   : 2023/05/25
Owner       : opentestcase043
Description :
        1.查询集群状态
        2.注入网路故障
        3.进行switchover -A 降备操作
        4.清除故障
        5.查询集群状态
        6.恢复初始状态
        7.注入网路故障
        8.进行switchover -A 降备操作
        9.清除故障
        10.查询集群状态
        11.清理环境
Expect      :
        1.集群状态正常
        2.注入故障成功
        3.降备操作成功
        4.清除故障成功
        5.成功
        6.集群状态正常，主备倒换
        7.注入故障成功
        8.降备操作失败
        9.清除故障成功
        10.集群状态正常
        11.清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from yat.test import Node

LOG = Logger()
Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == Primary_SH.get_node_num(), '单机环境不执行')
class ShareStorage(unittest.TestCase):

    def setUp(self):
        LOG.info('-----this is setup-----')
        LOG.info(f'-----{os.path.basename(__file__)} start-----')
        self.con = Constant()
        self.com = Common()
        self.pri_root_node = Node('PrimaryRoot')
        self.pri_node = Node('PrimaryDbUser')
        self.s1_sh = CommonSH('Standby1DbUser')

        LOG.info('----获取网卡----')
        network_card_cmd = 'ifconfig'
        LOG.info(network_card_cmd)
        network_card_result = self.pri_root_node.sh(
            network_card_cmd).result()
        network_card_list = network_card_result.split('\n\n')
        LOG.info(network_card_list)
        self.networkcard = ''
        for network_card_item in network_card_list:
            if self.pri_node.db_host in network_card_item:
                self.networkcard = network_card_item.split(':')[0].strip()
                LOG.info(self.networkcard)
                break

    def test_share_storage(self):
        text = '-----step1:查询集群状态; expect:集群状态正常-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)
        res = status.splitlines()[-1].split('|')[0].split('6001')[1]
        self.assertIn('P Primary Normal', res, '执行失败:' + text)

        text = '-----step2:注入网路故障; expect:注入故障成功-----'
        LOG.info(text)
        inject_command = f" rNet_loss (dev,rate) " \
                         f"values ({self.networkcard},5%)"
        cfe_thread = ComThread(
            self.com.execute_cfe,
            args=(self.pri_root_node, "inject", inject_command))
        cfe_thread.setDaemon(True)
        cfe_thread.start()
        cfe_thread.join()
        query_command = f" rNet_loss where dev={self.networkcard}"
        result = self.com.execute_cfe(self.pri_root_node, "query",
                                      query_command)
        LOG.info(result)
        self.assertIn("5%", result, '执行失败:' + text)

        text = '-----step3:进行switchover -A 降备操作; expect:降备操作成功-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('switchover', '-A')
        LOG.info(status)
        self.assertIn(self.con.cm_switchover_A_success_msg, status,
                      '执行失败:' + text)

        text = '-----step4:清除故障; expect:清除故障成功-----'
        LOG.info(text)
        clean_command = f"rNet_loss where dev={self.networkcard} and rate=5%"
        result = self.com.execute_cfe(self.pri_root_node, "clean",
                                      clean_command)
        self.assertNotIn("5%", result, '执行失败:' + text)

        text = '-----step5:查询集群状态; expect:集群状态正常，主备倒换-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)
        res = status.splitlines()[-1].split('|')[0].split('6001')[1]
        self.assertIn('P Standby Normal', res, '执行失败:' + text)

        text = '-----step6:恢复初始状态; expect:成功-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('switchover', '-a')
        LOG.info(status)
        self.assertIn(self.con.cm_switchover_success_msg, status,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)
        res = status.splitlines()[-1].split('|')[0].split('6001')[-1]
        self.assertIn('P Primary Normal', res, '执行失败:' + text)

        text = '-----step7:注入网路故障; expect:注入故障成功-----'
        LOG.info(text)
        inject_command = f" rNet_loss (dev,rate) " \
                         f"values ({self.networkcard},50%)"
        cfe_thread = ComThread(
            self.com.execute_cfe,
            args=(self.pri_root_node, "inject", inject_command))
        cfe_thread.setDaemon(True)
        cfe_thread.start()
        cfe_thread.join()
        query_command = f" rNet_loss where dev={self.networkcard}"
        result = self.com.execute_cfe(self.pri_root_node, "query",
                                      query_command)
        LOG.info(result)
        self.assertIn("50%", result, '执行失败:' + text)

        text = '-----step8:进行switchover -A 降备操作; expect:降备操作失败-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('switchover', '-A')
        LOG.info(status)
        self.assertNotIn(self.con.cm_switchover_A_success_msg, status,
                         '执行失败:' + text)

        text = '-----step9:清除故障; expect:清除故障成功-----'
        LOG.info(text)
        clean_command = f"rNet_loss where dev={self.networkcard} and rate=50%"
        result = self.com.execute_cfe(self.pri_root_node, "clean",
                                      clean_command)
        self.assertNotIn("50%", result, '执行失败:' + text)

        text = '-----step10:查询集群状态; expect:集群状态正常-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('stop')
        self.assertIn(self.con.cm_stop_success_msg, status,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('start')
        self.assertIn(self.con.cm_start_success_msg, status,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)
        res = status.splitlines()[-1].split('|')[0].split('6001')[1]
        self.assertIn('P Standby Normal', res, '执行失败:' + text)

    def tearDown(self):
        text = '-----this is tearDown-----'
        LOG.info(text)
        text = '-----step11:清理环境; expect:清理环境成功-----'
        LOG.info(text)
        self.status1 = ''
        query_command = f" rNet_loss where dev={self.networkcard}"
        result = self.com.execute_cfe(self.pri_root_node, "query",
                                      query_command)
        LOG.info(result)
        if "%" in result:
            clean_command = f"rNet_loss where dev={self.networkcard} " \
                            f"and rate=5%"
            self.com.execute_cfe(self.pri_root_node, "clean", clean_command)
            self.status1 = self.com.execute_cfe(self.pri_root_node, "query",
                                                query_command)
        status2 = Primary_SH.exec_cm_ctl('stop')
        status3 = Primary_SH.exec_cm_ctl('start')
        status4 = Primary_SH.exec_cm_ctl('switchover', '-a')
        status5 = Primary_SH.exec_cm_ctl('query', '-Cv')
        if "%" in self.status1:
            LOG.info(self.status1)
        LOG.info(status2)
        LOG.info(status3)
        LOG.info(status4)
        LOG.info(status5)
        if "%" in result:
            self.assertNotIn("%", self.status1, '执行失败:' + text)
        self.assertIn(self.con.cm_stop_success_msg, status2,
                      '执行失败:' + text)
        self.assertIn(self.con.cm_start_success_msg, status3,
                      '执行失败:' + text)
        self.assertIn(self.con.cm_switchover_success_msg, status4,
                      '执行失败:' + text)
        self.assertIn('cluster_state   : Normal', status5, '执行失败:' + text)
        res = status5.splitlines()[-1].split('|')[0].split('6001')[-1]
        self.assertIn('P Primary Normal', res, '执行失败:' + text)
        LOG.info(f'-----{os.path.basename(__file__)} end-----')
